package com.chinasoft.controller;

import com.chinasoft.dao.Impl.UserDAOImpl;
import com.chinasoft.dao.UserDAO;
import com.chinasoft.entity.User;
import com.chinasoft.utils.FileUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by YE on 2018/5/10.
 */
@WebServlet(name = "UploadServlet", urlPatterns = {"/upload"})
public class UploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        UserDAO userDAO=new UserDAOImpl();
        DiskFileItemFactory disk = new DiskFileItemFactory();
        ServletFileUpload up = new ServletFileUpload(disk);
        User user=null;
        String upop=request.getParameter("upop");
        if(upop.equals("avatar")){
            String path = getServletContext().getRealPath("/avatar");
            try{
                List<FileItem> list=up.parseRequest(request);
                for(FileItem file:list){
                    if(file.isFormField()){
                        int uid= Integer.parseInt(file.getString());
                        user=userDAO.selectUser(uid);
                    }else{
                        String fileName=file.getName();
                        String fileType=file.getContentType();
                        InputStream in=file.getInputStream();
                        int size=in.available();
                        File outDir =new File("path");
                        if(!outDir.exists()){
                            outDir.mkdirs();
                        }
                        String[] fn=fileName.split("\\.");
                        StringBuffer filename=new StringBuffer();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
                        filename.append(sdf.format(new Date()));
                        filename.append(".");
                        filename.append(fn[fn.length-1]);
                        if(FileUtils.find(path,filename.toString())){
                            out.println("<script>alert('上传失败！文件名重复，请稍候重试!');location.href='avatar.jsp';</script>");
                        }else{
                            OutputStream os=new FileOutputStream(path+"/"+filename.toString());
                            byte[] b=new byte[1024];
                            int len=0;
                            while((len=in.read(b))!=-1){
                                os.write(b,0,len);
                            }
                            user.setAvatar(filename.toString());
                            userDAO.updateAvatar(user);
                            request.getSession().removeAttribute("user");
                            request.getSession().setAttribute("user",user);
                            os.flush();
                            os.close();
                            out.println("<script>alert('上传成功!');location.href='avatar.jsp';</script>");
                        }
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
